//
//  DXCompaseView.swift
//  weiBoOfSwift
//
//  Created by simon on 15/12/13.
//  Copyright © 2015年 simon. All rights reserved.
//

import UIKit
import pop

let KcompBtnW:CGFloat = 80
let KcompBtnH:CGFloat = 110
let KcompBtnColCount = 3
let KcompBtnMargin = ( KScreenW - CGFloat(KcompBtnColCount) * KcompBtnW ) / CGFloat(KcompBtnColCount + 1)
class DXCompaseView: UIView {
 
    private var targetController:UIViewController?
    private var compseButtons = [DXCompseBtn]()

    override init(frame: CGRect) {
       
        super.init(frame: CGRectMake(0, 0, KScreenW, KScreenH))
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    MARK:初始化UI
    private func setUpUI(){
    backgroundColor = UIColor.orangeColor()
        
//        添加控件
        addSubview(bgImgView)
        addSubview(sloganImgView)
        
//        添加Btn
        addCompseBtn()
//        bgImgView添加约束
        bgImgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsMake(0, 0, 0, 0))
        }
        sloganImgView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
       
        
    }
    

// MARK:   屏幕的点击事件
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for (i,button) in compseButtons.reverse().enumerate(){
            startAnimation(button, index: i,isuping: false)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.75 * Double( NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
             self.removeFromSuperview()
        }
        
    }
    
//  MARK:  添加到上层控制
    func show(targetController:UIViewController){
       self.targetController = targetController
        targetController.view.addSubview(self)
        
        for (i,button) in compseButtons.enumerate(){
            startAnimation(button, index: i,isuping: true)
        }
        
    }
    
//    MARK:执行动画
    private func startAnimation(button:DXCompseBtn,index:Int,isuping:Bool){
    
        let anima = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        let y = isuping ? button.center.y - 350 : button.center.y + 350
        
        anima.toValue =   NSValue(CGPoint: CGPointMake(button.center.x, y))
        anima.springSpeed = 19
        anima.springBounciness = 10
        anima.beginTime = CACurrentMediaTime() + Double(index)*0.09
        button.pop_addAnimation(anima, forKey: nil)
    }
    
//    MARK:添加compseBtn
  private func addCompseBtn(){
     for (i,model) in self.compseBtns.enumerate(){
        
        let col = i / KcompBtnColCount
        let row = i % KcompBtnColCount
        
        let x = CGFloat(row) * KcompBtnW + CGFloat(row + 1) * KcompBtnMargin
        let y = CGFloat(col) * KcompBtnH + CGFloat(col + 1) * KcompBtnMargin + KScreenH
        
        let frame = CGRectMake(x, y, KcompBtnW, KcompBtnH)
        let compBtn = DXCompseBtn()
        compBtn.frame = frame
        compBtn.addTarget(self, action: "compBtnClick:", forControlEvents: .TouchUpInside)
        compBtn.tag = i
    compBtn.setImage(UIImage(named:model.icon!), forState: .Normal)
    compBtn.setTitle(model.title, forState: .Normal)
    compBtn.titleLabel?.font = UIFont.systemFontOfSize(14)
    compBtn.setTitleColor(UIColor.grayColor(), forState: .Normal)
//     添加到数组中
    compseButtons.append(compBtn)
    addSubview(compBtn)
    
 }
}
//    MARK:compseBtn点击事件弹出控制器
    @objc private func compBtnClick(sender:UIButton){
    
        UIView.animateWithDuration(0.25, animations: { () -> Void in
    for btn in self.compseButtons {
        if btn == sender{
            btn.transform = CGAffineTransformMakeScale(1.5, 1.5)
        }else{
         btn.transform = CGAffineTransformMakeScale(0.5, 0.5)
        }
    }
            }) { (_) -> Void in
                
         UIView.animateWithDuration(0.5, animations: { () -> Void in
            for btn in self.compseButtons {
                btn.transform = CGAffineTransformIdentity
            }

            }, completion: { (_) -> Void in
//                动画完成,弹出控制器
  if  let VcString = self.compseBtns[sender.tag].targetCotrollerName {
                
   let targetVcName = "weiBoOfSwift.\(VcString)"
   
   let clas = NSClassFromString(targetVcName) as! UIViewController.Type
   
    let targetVc = clas.init()
                
    let vc = DXNavigationController(rootViewController: targetVc)
                
    self.targetController?.presentViewController(vc,
        animated: true,
        completion: { () -> Void in
         self.removeFromSuperview()
                })
            }
         })
    }
}
    
//    MARK:懒加载控件
    lazy var bgImgView:UIImageView = UIImageView(image:UIImage.screenShotEffectImg())
    
    lazy var sloganImgView:UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    lazy var compseBtns:[DXCompseBtnModel] = {
      let filePath = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
      let dictArray = NSArray(contentsOfFile: filePath)
        var tempArray = [DXCompseBtnModel]()
        for dict in dictArray! {
            let model = DXCompseBtnModel(dict: dict as! [String : AnyObject])
        tempArray.append(model)
        }
    return tempArray
    }()
    
    
}
